package com.my_musc_service.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.my_musc_service.entity.RegisterVo;
import com.my_musc_service.entity.User;
import com.my_musc_service.exception.CustomException;
import com.my_musc_service.service.RegisterService;
import com.my_musc_service.service.UserService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.UUID;

/**
 * @author zhudunfeng
 * @date 2021/6/24 22:12
 */
@Service
public class RegisterServiceImpl implements RegisterService {

    @Autowired
    private UserService userService;

    @Override
    public void register(RegisterVo registerVo) {
        String userName = registerVo.getUserName();
        String nickName = registerVo.getNickName();
        String password = registerVo.getPassword();
        String phone = registerVo.getPhone();
        Integer sex = registerVo.getSex();

        //校验参数
//        if (StringUtils.isEmpty(userName)
//                || !FormUtils.isMobile(phone)
//                || StringUtils.isEmpty(password)
//                || StringUtils.isEmpty(nickName)) {
        if (StringUtils.isEmpty(userName)
                || StringUtils.isEmpty(password)) {
            throw new CustomException("参数不正确");
        }

        //查看用户名是否被注册
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        userQueryWrapper.eq("user_name", userName);
        BaseMapper<User> baseMapper = userService.getBaseMapper();
        Integer count = baseMapper.selectCount(userQueryWrapper);

        if (count > 0) {
            throw new CustomException("用户名已被注册");
        }
        //查看手机号码是否被注册
//        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
//        userQueryWrapper.eq("phone", phone);
//        Integer count = baseMapper.selectCount(userQueryWrapper);
//
//        if(count>0){
//            throw new CustomException("手机号已被注册");
//        }


        //注册
        User user = new User();

        //2.生成盐
        String salt = UUID.randomUUID().toString().substring(0, 6);
        user.setSalt(salt);

        //3.加盐加密
        user.setPassword(DigestUtils.md5Hex(password + salt));

        user.setUserName(userName);
        user.setNickName(nickName);
        user.setPhone(phone);
//        user.setPassword(MD5.encrypt(password));
        user.setSex(sex);
        baseMapper.insert(user);

    }
}
